import * as $filter from '@/filters'
import request from '@/utils/request';
import {
  downloadFile
} from 'ui-component-v4/lib/dg-utils/funcs.js';
import {
  queryCurrentEncryptSfzh
} from '@/api/common';
const {
  getSetting
} = window.systemParamsUtils;

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null;
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
  let date;
  if (typeof time === 'object') {
    date = time;
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000;
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value];
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value;
    }
    return value || 0;
  });
  return time_str;
}

// 格式化时间
export function formatTime(time, option) {
  time = +time * 1000;
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return '刚刚';
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前';
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前';
  } else if (diff < 3600 * 24 * 2) {
    return '1天前';
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分';
  }
}

// 将url的参数转为对象
// 不传默认获取当前浏览器地址的参数
export function getQueryObject(url) {
  url = url == null ? window.location.href : url;
  const search = url.substring(url.lastIndexOf('?') + 1);
  const obj = {};
  const reg = /([^?&=]+)=([^?&=]*)/g;
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1);
    let val = decodeURIComponent($2);
    val = String(val);
    obj[name] = val;
    return rs;
  });
  return obj;
}

export function param2Obj(url) {
  const search = url.split('?')[1];
  if (!search) {
    return {};
  }
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
    .replace(/"/g, '\\"')
    .replace(/&/g, '","')
    .replace(/=/g, '":"') +
    '"}'
  );
}

export function html2Text(val) {
  const div = document.createElement('div');
  div.innerHTML = val;
  return div.textContent || div.innerText;
}

export const pickerOptions = [{
    text: '今天',
    onClick(picker) {
      const end = new Date();
      const start = new Date(new Date().toDateString());
      end.setTime(start.getTime());
      picker.$emit('pick', [start, end]);
    }
  },
  {
    text: '最近一周',
    onClick(picker) {
      const end = new Date(new Date().toDateString());
      const start = new Date();
      start.setTime(end.getTime() - 3600 * 1000 * 24 * 7);
      picker.$emit('pick', [start, end]);
    }
  },
  {
    text: '最近一个月',
    onClick(picker) {
      const end = new Date(new Date().toDateString());
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      picker.$emit('pick', [start, end]);
    }
  },
  {
    text: '最近三个月',
    onClick(picker) {
      const end = new Date(new Date().toDateString());
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      picker.$emit('pick', [start, end]);
    }
  }
];

export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90;
  } else {
    return new Date(new Date().toDateString());
  }
}

export function debounce(func, wait = 200, immediate) {
  let timeout, args, context, timestamp, result;

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp;

    // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      }
    }
  };

  return function (...args) {
    context = this;
    timestamp = +new Date();
    const callNow = immediate && !timeout;
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'shallowClone');
  }
  const targetObj = source.constructor === Array ? [] : {};
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys]);
    } else {
      targetObj[keys] = source[keys];
    }
  });
  return targetObj;
}

export function uniqueArr(arr) {
  return Array.from(new Set(arr));
}

/**
 * @func 使用身份证进行计算年龄
 * @param {String} val 需要年龄的身份证号码
 * @returns {String} 返回计算的年龄
 */
export function showYear(val) {
  if (!val) return;
  let len = val.length;
  let myDate = new Date();
  let age = 0;
  if (len === 18) {
    age = myDate.getFullYear() - val.substring(6, 10);
    return age;
  } else if (len === 15) {
    age = myDate.getFullYear() - val.substring(6, 8) - 1901;
    return age;
  }
}

/**
 *
 * 使用身份证判断性别
 * @param {String} val 判断性别的身份证号码
 * @returns {String} 返回判断的性别
 */
export function diffGender(val) {
  if (val == null || val == '' || val == undefined) {
    return '';
  }
  if (parseInt(val.substr(16, 1)) % 2 == 1) {
    return '男';
  } else {
    return '女';
  }
}

// 自定义转化函数
Date.prototype.Format = function (fmt) {
  let o = {
    'M+': this.getMonth() + 1, // 月份
    'd+': this.getDate(), // 日
    'h+': this.getHours(), // 小时
    'm+': this.getMinutes(), // 分
    's+': this.getSeconds(), // 秒
    'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
    S: this.getMilliseconds() // 毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
  for (let k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
  return fmt;
};

/**
 * @MethodName: 生成随机字符串作为key
 * @param { Number } len 随机数长度
 * @return { string }
 **/
export function generateKey(len = 32) {
  const $chars = 'abcdefhijkmnprstwxyz2345678';
  const result = [];
  for (let i = 0; i < len; i++) {
    result.push($chars.charAt((Math.random() * 27) << 0));
  }
  return result.join('');
}

/**
 * @MethodName: 将时间转化为后端需要的格式
 * @param { Number } 时间
 * @return { string }
 **/
export function handleTimeStr(val) {
  let dateList = [];
  if (val) {
    val.forEach((item, index) => {
      let time = $filter.longTime2Str(item, 'yyyyMMdd')
      const second = index ? '235959' : '000000';
      dateList.push(time + second);
    });
  }
  return dateList.toString();
}

/**
 * @MethodName: 下载文件
 * @param { Object } 文件信息
 * @return { string }
 **/
export const fileDownLoad = async options => {
  const res = await request({
    ...options,
    responseType: 'arraybuffer'
  });
  let blob = new Blob([res]);
  const href = window.URL.createObjectURL(blob); // 创建下载的链接
  downloadFile(options.fileName, href);
  return true;
};

/**
 * @MethodName: 下载文件
 * @param { Object } 文件信息
 * @return { string }
 **/
export function handleFilestream(response, name = 'file.xlsx') {
  let filename = name || 'filename';
  const blob = new Blob([response.data], {
    type: response.headers['content-type']
  });
  const disposition = response.headers['content-disposition'];
  if (!name && disposition) {
    filename = disposition.split('filename=')[1];
    filename = decodeURIComponent(filename);
  }
  const href = window.URL.createObjectURL(blob); // 创建下载的链接
  downloadFile(filename, href);
}

/**
 * @MethodName: 跳转至档案系统
 * @param { String } 身份证号
 * @return { string }
 **/
export function routeToArchive(sfzh) {
  queryCurrentEncryptSfzh().then(res => {
    const routeUrl = `${getSetting("ARCHIVE_URL")}?sfzh=${sfzh}&yhsfzh=${res.data}`;
    window.open(routeUrl, '_blank');
    // http: //192.168.0.125:8080/index.html?sfzh={事件人员列表的明文身份证号}&yhsfzh={当前登录用户的加密串}】
  })
}

/**
 * @MethodName: 跳转至对应详情
 * @param { Object } row 单条信息
 * @return { string }
 **/
export function routeToClueDetail(row) {
  // 来源类型：0-外部来文；1-要情上报；2-线索上报；3-110报警信息（情报）-研判；4-线索（情报特有）；5-110报警处理（续报）
  const routeName = {
    0: 'ExterCommunDetail',
    1: 'ImpDetail',
    2: 'AllBureausDetail',
    3: 'PoliceNewsDetail',
    4: 'LocalBureausDetail',
    5: 'PoliceApprovalDetail'
  };
  const routeData = this.$router.resolve({
    name: routeName[row.sourceType],
    params: {
      // id: id || row.id
      id:row.flowId
    }
  });
  window.open(routeData.href, '_blank');
}